package practise;

public class IsBalanced {
    public boolean isBalanced(TreeNode root) {
        if(root == null) {
            return true;
        }
        return getMaxDepth(root) >= 0;
    }

    public int getMaxDepth(TreeNode node) {
        if(node == null) {
            return 0;
        }

        int leftHeight = getMaxDepth(node.left);
        int rightHeight = getMaxDepth(node.right);
        return leftHeight < 0 || rightHeight < 0 || Math.abs(leftHeight - rightHeight) > 1 ? -2 : (Math.max(leftHeight, rightHeight) + 1);
    }
}
